﻿/// <reference path="../libs/jquery-1.8.2-vsdoc.js" />
var SCA = SCA || {};
SCA.UI = SCA.UI || {};
SCA.UI.DocumentTemplatesMappings = SCA.UI.DocumentTemplatesMappings || {};

SCA.UI.DocumentTemplatesMappings.Dialog = function (DocumentTemplatesMappingsTable) {
    this.DocumentTemplatesMappingsTable = DocumentTemplatesMappingsTable;
    this.LocationSelectionDialog;

    var thisContext = this;

    var FOLDER_TYPE_WEB = "Sobiens.Connectors.Entities.SharePoint.SPWeb";
    var FOLDER_TYPE_LIST = " Sobiens.Connectors.Entities.SharePoint.SPList";
    var FOLDER_TYPE_FOLDER = "Sobiens.Connectors.Entities.SharePoint.SPFolder";

    this.SelectedFolderType = null;

    this.Setup = function () {
        jQuery("#DocumentTemplateMappingEditDialog").on("dialogclose", function (event, ui) { jQuery(".validity-modal-msg").hide(); });
        jQuery("#ButtonDocumentTemplateMappingDialogLocation").click(function () { thisContext.OpenLocationTree() });
    }

    this.New = function () {
        GetHiddenInputIndex().val("-1");
        FillAllDropDownLists();
        GetInputLocation().val("");
        GetCheckBoxAllowSelectSubfolder().attr("checked", false);
        GetDropDownContentType().empty();
        this.SelectedFolderType = null;
    }

    this.Load = function (index) {
        try {
            if (SCA.AppConfiguration.DocumentTemplateMappings == null)
                return;

            var documentTemplateMapping = GetDocumentTemplateMapping(index);

            FillAllDropDownLists();
            GetDropDownTemplate().val(documentTemplateMapping.DocumentTemplateID);
            GetDropDownSiteSetting().val(documentTemplateMapping.SiteSettingID);
            GetInputLocation().val(documentTemplateMapping.FolderPath);

            var path = documentTemplateMapping.FolderPath;
            var siteSettingUrl = GetDropDownSiteSettingSelectedText();
            this.SelectedFolderType = documentTemplateMapping.FolderType;


            //fill the CT dropdownlists
            SCA.DAL.SP.GetWebUrlFromUrl(siteSettingUrl, path, Function.createDelegate(this, function (webUrl) {
                var listName = this.GetListNameFromAbsoluteUrl(webUrl, path);
                var list = new SCA.DAL.List(listName, webUrl);
                list.Load(function () {
                    FillDropDownList(list.contentTypeCollection, GetDropDownContentType(), function (item) { return item.id; }, function (item) { return item.title; });
                    GetDropDownContentType().val(documentTemplateMapping.ContentTypeID);
                });

            }),
            function (data) { console.log("SCA.UI.DocumentTemplatesMappings.Dialog: " + data); });

            GetCheckBoxAllowSelectSubfolder().attr("checked", documentTemplateMapping.AllowToSelectSubFolders);

            GetHiddenInputIndex().val(index);
        }
        catch (ex) {
            alert("SCA.UI.DocumentTemplatesMappings.Dialog: " + ex.message);
        }
    }

    this.GetListNameFromAbsoluteUrl = function(webSiteUrl, absoluteUrl){
        var n = webSiteUrl.length;
        var charsToRemove = (webSiteUrl.charAt(n-1) !='/') ? n + 1 : n;

        var partialUrl = absoluteUrl.substring(charsToRemove).toLowerCase();
        
        var tokensOfPartialUrl = partialUrl.split("/");
        
        var listName = (partialUrl.indexOf("lists/") == 0) ? tokensOfPartialUrl[1] : tokensOfPartialUrl[0];

        return listName;
    }


    this.OpenLocationTree = function()
    {
        var treeParams = {
            allowSelectWeb: false,
            allowSelectList: true,
            allowSelectFolder: GetCheckBoxAllowSelectSubfolder().is(':checked'),
            exploreDepth: GetCheckBoxAllowSelectSubfolder().is(':checked') ? "Folder" : "List"
        }
        
        this.LocationSelectionDialog = new SCA.UI.LocationSelection.Dialog("Location selection", GetDropDownSiteSettingSelectedText(), treeParams, SelectLocationCallback);
        this.LocationSelectionDialog.Open();
    }

    var SelectLocationCallback = function (result) {
        if (result != null) {
            GetInputLocation().val(result.absoluteUrl);

            this.SelectedFolderType = (result instanceof SCA.DAL.List)
                                        ? FOLDER_TYPE_LIST
                                        : (result instanceof SCA.DAL.Folder)
                                            ? FOLDER_TYPE_FOLDER
                                            : null;

            result = (result instanceof SCA.DAL.List) ? result : result.parentList;
            FillDropDownList(result.contentTypeCollection, GetDropDownContentType(), function (item) { return item.id; }, function (item) { return item.title; });
        }
    }

    var FillAllDropDownLists = function()
    {
        FillDropDownList(SCA.AppConfiguration.DocumentTemplates, GetDropDownTemplate(), function (item) { return item.ID; }, function (item) { return item.ApplicationType; });
        FillDropDownList(SCA.AppConfiguration.SiteSettings, GetDropDownSiteSetting(), function (item) { return item.ID; }, function (item) { return item.Url; });
    }

    var FillDropDownList = function(listOfItems, dropDownList, valueDelegate, textDelegate)
    {
        dropDownList.html("");

        if ((listOfItems != null) && (listOfItems.length > 0))
            for (var i = 0; i < listOfItems.length; i++) {
                var item = listOfItems[i];
                jQuery("<option value='" + valueDelegate(item) + "'>" + textDelegate(item) + "</option>").appendTo(dropDownList);
            }
    }
   
    this.Validate = function () {

        jQuery.validity.setup({ outputMode: "modal" });

        jQuery.validity.start();
        GetDropDownTemplate().require("Required.");
       //TODO: location and content type

        var result = jQuery.validity.end();

        return result.valid;
    }

    this.Close = function () {
        jQuery("#DocumentTemplateMappingEditDialog").dialog("close");
    }

    this.Save = function () {

        var isValid = this.Validate();
        if (!isValid)
            return;

        var index = GetHiddenInputIndex().val();

        var isNewItem = false;
        if (index == -1) //it's a new doc template mapping
        {
            index = SCA.AppConfiguration.DocumentTemplateMappings.push({}) - 1;
            isNewItem = true;
        }

        var docTemplateMapping = GetDocumentTemplateMapping(index);

        docTemplateMapping.ApplicationType = GetDropDownTemplateSelectedText();
        docTemplateMapping.DocumentTemplateID = GetDropDownTemplate().val();
        docTemplateMapping.SiteSettingID = GetDropDownSiteSetting().val();
        docTemplateMapping.FolderPath = GetInputLocation().val();
        docTemplateMapping.FolderType = this.SelectedFolderType;
        docTemplateMapping.AllowToSelectSubFolders = GetCheckBoxAllowSelectSubfolder().is(':checked');
        docTemplateMapping.ContentTypeID = GetDropDownContentType().val();
        docTemplateMapping.ContentTypeName = GetDropDownContentTypeSelectedText();

        if (isNewItem) {
            this.DocumentTemplatesMappingsTable.AddRow(index);
        }
        else {
            this.DocumentTemplatesMappingsTable.RefreshRow(index);
        }

        this.Close();
    }

    var GetDocumentTemplateMapping = function (index) {
        return SCA.AppConfiguration.DocumentTemplateMappings[index];
    }

    //var GetDialog = function () {
    //    return jQuery(....);
    //}

    var GetDropDownTemplate = function () {
        return jQuery("#DropDownDocumentTemplateMappingDialogTemplate");
    }

    var GetDropDownTemplateSelectedText = function(){
        return jQuery("#DropDownDocumentTemplateMappingDialogTemplate option:selected").text();
    }

    var GetDropDownSiteSetting = function () {
        return jQuery("#DropDownDocumentTemplateMappingDialogSiteSetting");
    }

    var GetDropDownSiteSettingSelectedText = function()
    {
        return jQuery("#DropDownDocumentTemplateMappingDialogSiteSetting option:selected").text();
    }


    var GetInputLocation = function (){
        return jQuery("#InputDocumentTemplateMappingDialogLocation");
    }

    var GetCheckBoxAllowSelectSubfolder = function () {
        return jQuery("#CheckBoxDocumentTemplateMappingDialogAllowSelectSubfolder");
    }

    var GetDropDownContentType = function () {
        return jQuery("#DropDownDocumentTemplateDialogMappingContentType");
    }

    var GetDropDownContentTypeSelectedText = function () {
        return jQuery("#DropDownDocumentTemplateDialogMappingContentType option:selected").text();
    }

    var GetHiddenInputIndex = function () {
        return jQuery("#HiddenFieldDocumentTemplateMappingDialogCurrentIndex");
    }

    this.Setup();
};